# -*- coding: utf-8 -*-
import wx
import os, sys

import win32api
import win32con
import win32gui
import dbhelper

class RememberFloatWnd(wx.Frame):
    def __init__(self, *args, **kwds):
        self._SetMemberData(kwds["NoteID"]) #init the data and remove from the kwds
        del kwds["NoteID"] 
        kwds["style"] = (~(wx.RESIZE_BORDER))  &(~wx.VSCROLL) &( wx.FULL_REPAINT_ON_RESIZE | wx.SIMPLE_BORDER |wx.FRAME_NO_TASKBAR| wx.STAY_ON_TOP )
        wx.Frame.__init__(self, *args, **kwds)
        self.SetBackgroundColour(wx.Colour(255, 255, 168))    
        self.CentreOnScreen()  
        
        self._SetWndTransparent()
        self._CreateSubWidget()
        
    def _SetWndTransparent(self):
        hwnd = self.GetHandle() 
        _winlib = win32api.LoadLibrary("user32") 
        pSetLayeredWindowAttributes = win32api.GetProcAddress(_winlib,"SetLayeredWindowAttributes") 
        exstyle = win32api.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) 
        if 0 == (exstyle & 0x80000):
            win32api.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, exstyle | 0x80000)          
            win32gui.SetLayeredWindowAttributes(hwnd, 0, 200, 2) #set the transparent style
    def _CreateSubWidget(self):
        self.vMainSizer = wx.BoxSizer(wx.VERTICAL)
        
        self.EditText = wx.TextCtrl(self, -1, "", style=(wx.TE_MULTILINE|wx.TE_RICH|wx.TE_LEFT|wx.TE_WORDWRAP|wx.NO_BORDER|wx.TE_NO_VSCROLL)&(~wx.TE_PROCESS_TAB))
        self.EditText.SetBackgroundColour(wx.Colour(255, 255, 168))
        self.EditText.Bind(wx.EVT_TEXT, self.OnEditText)
        self.EditText.Bind(wx.EVT_CHAR, self.OnChar)
        self.EditText.Bind(wx.EVT_LEFT_DOWN, self.OnEditLeftDown)
        self.EditText.Bind(wx.EVT_LEFT_UP, self.OnEditLeftUp)
        self.EditText.Bind(wx.EVT_MOTION, self.OnEditMotion)
        self.EditText.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)
        
        self._CreateManu()
        self.EditText.Bind(wx.EVT_RIGHT_DOWN, self.OnShowManu)
                
        self.EditTag = wx.TextCtrl(self, -1, "", style=wx.TE_LEFT|wx.NO_BORDER|wx.TE_RICH)
        self.EditTag.SetBackgroundColour(wx.Colour(255, 255, 0))
        self.EditTag.Bind(wx.EVT_KILL_FOCUS, self.OnLoseFocus)
        self.EditTag.Bind(wx.EVT_CHAR, self.OnChar)
        
        #olPoint = self.EditTag.GetFont().GetPointSize()  # can not set the style for only one line textctrl
        #newFont = wx.Font(olPoint, wx.ROMAN, wx.ITALIC, wx.BOLD)
        #self.EditTag.SetDefaultStyle(wx.TextAttr("BLUE", wx.NullColour, newFont))
        
        
        self.vMainSizer.Add(self.EditText, 0, wx.ALL, 3)
        self.vMainSizer.Add(self.EditTag, 0, wx.EXPAND|wx.LEFT|wx.RIGHT, 3)
        
        
        if self.Content:
            self.EditText.Value = self.Content
        if self.Tags:
            self.EditTag.Value = self.Tags
        
        self.EditText.SetInitialSize(self._CaculatEditTextSize())
        
        self.SetSizer(self.vMainSizer)
        self.Fit()
    def OnChar(self, event):
        if event.GetKeyCode() == wx.WXK_TAB:
            if event.EventObject == self.EditText:
                self.EditTag.SetFocus()
            if event.EventObject == self.EditTag:
                self.EditText.SetFocus()
        else:
            event.Skip()
    def _CaculatEditTextSize(self):
        lines = self.Content.split("\n")
        totoalLineNum = len(lines)
        
        dc = wx.MemoryDC() 
        width,height,lineheight = dc.GetMultiLineTextExtent(self.Content, self.EditText.GetFont())
        if 50 > width: width = 100
        if 1  > height: height = 1
        width = width + 20
        height =  height + totoalLineNum * 2
        return (width,height)
        
    def _SetMemberData(self, noteid= None):
        self.Content = ""
        self.Tags = ""
        self.NoteID = None
        
        if None == noteid: return 
        
        db = dbhelper.DbHelper('test.db',new=False)
        for note in db.GetNotesByID(noteid):
            self.NoteID = note.get('ID')
            self.Tags = note.get('tag')
            self.Content = note.get('content')
        db.Disconnect()
            
    def OnEditText(self, event):
        self.Freeze()
        self.EditText.Freeze()
        self.Content = self.EditText.GetValue()
        self.EditText.SetInitialSize(self._CaculatEditTextSize())
        self.Fit()
        self.EditText.Thaw()
        self.Thaw()
        event.Skip()


    def OnEditLeftDown(self, event):
        if event.EventObject != self.EditText: return
        if event.EventObject==self.EditText:
            self.EditText.CaptureMouse()
        mouse=wx.GetMousePosition()
        frame=self.GetPosition()
        self.delta=wx.Point(mouse.x-frame.x,mouse.y-frame.y)
        event.Skip()
    def OnEditMotion(self, event):      
        if event.EventObject != self.EditText: return
        if event.Dragging() and event.LeftIsDown():
             mouse=wx.GetMousePosition()
             self.Move((mouse.x-self.delta.x,mouse.y-self.delta.y))
        event.Skip()
    def OnEditLeftUp(self,event):
        if event.EventObject != self.EditText: return
        if self.EditText.HasCapture():
            self.EditText.ReleaseMouse()
        event.Skip()
    def OnLoseFocus(self, event):
        self.Content = self.EditText.GetValue()
        self.Tags = self.EditTag.GetValue()
        self._SaveToDB()
        event.Skip()
    def _SaveToDB(self):
        data = {}
        data.update( {'content': self.Content} )
        data.update( {'tag':self.Tags} )
        data.update( {'NoteID': self.NoteID} )
        db = dbhelper.DbHelper('test.db',new=False)
        db.SaveNote(data)
        self.NoteID = data['NoteID']
        db.Disconnect()
        
    def _CreateManu(self):
        self.btnMenu = wx.Menu()    
        self.btnMenu.Append(1, "Close")
        self.EditText.Bind(wx.EVT_MENU, self.OnCloseWnd, id = 1)
    def OnShowManu(self, event):
        self.EditText.PopupMenu(self.btnMenu)
        
    def OnCloseWnd(self, event):
        self.GetParent().RemoveRememberFloatWndRef(self)
        self.Close()
        
if __name__ == "__main__":
   app = wx.PySimpleApp()
   main = RememberFloatWnd(None, -1, "Notes", Content = "adfasdf", Tag = "af", NoteID = 0)
   main.Show()
   app.MainLoop()
    
